//
//  GRMonthBillViewController.m
//  YC_GRice
//
//  Created by luojinrong11 on 2018/7/27.
//  Copyright © 2018年 YeCai. All rights reserved.
//

#import "GRMonthBillViewController.h"
#import "GRMonthBillTableViewCell.h"
#import "GRAllBillAction.h"
#import "GRRepaymentViewController.h"
#import "GRAllBillViewController.h"
//#import "GRInTheInstallmentViewController.h"
#import "MSTabBarController.h"
@interface GRMonthBillViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (strong, nonatomic) IBOutlet UIView *footView;

@property (strong, nonatomic) IBOutlet UIView *headerView;

@property (weak, nonatomic) IBOutlet UITableView *monthBillList;
@property (weak, nonatomic) IBOutlet UIView *outstandingView;
@property (weak, nonatomic) IBOutlet UIView *alreadyPayView;

@property (weak, nonatomic) IBOutlet UIButton *payBt;
@property (weak, nonatomic) IBOutlet UILabel *saveTimeLabel;

@property (weak, nonatomic) IBOutlet UILabel *outDateLabel;

@property (weak, nonatomic) IBOutlet UILabel *lastDayLabel;

@property (weak, nonatomic) IBOutlet UIView *OverdueView;
@property (weak, nonatomic) IBOutlet UILabel *OverdueLabel;
@property (weak, nonatomic) IBOutlet UILabel *totalPriceLabel;

@property(nonatomic,strong)NSArray * cellTypeArr;
@property(nonatomic,strong)GRAllBillAction * monthBillAction;
@property(nonatomic,strong)GRAllBillModel *billModel;

@property (weak, nonatomic) IBOutlet UIButton *lastMonth;

@property (weak, nonatomic) IBOutlet UIButton *nextMonth;
@property (weak, nonatomic) IBOutlet UILabel *currentDateLabel;
@property (weak, nonatomic) IBOutlet UIImageView *nextArrow;
@property (weak, nonatomic) IBOutlet UILabel *overdueTipLabel;

@property (weak, nonatomic) IBOutlet UIImageView *allOverdueImage;
@property (weak, nonatomic) IBOutlet UILabel *allOverdueTip;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *monthListTop;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomViewHeght;

@property (weak, nonatomic) IBOutlet UIView *placeIamgeview;

@property (weak, nonatomic) IBOutlet UIView *noBillView;

@property (weak, nonatomic) IBOutlet UIImageView *lastArrow;

@end

@implementation GRMonthBillViewController
-(GRAllBillAction *)monthBillAction {
    if (!_monthBillAction) {
        _monthBillAction = [[GRAllBillAction alloc]init];
    }
    return _monthBillAction;

}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self.monthBillList registerNib:[UINib nibWithNibName:@"GRMonthBillTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"monthBillCell"];
    self.navigationItem.title = @"账单";
    if (_isBill) {
        self.month = [self getCurrentMonth];
    }
    [self loadData];
}

-(NSString *)getCurrentMonth{
    NSDate * date =  [NSDate date];
    NSDateFormatter * dateFormat = [[NSDateFormatter alloc]init];
    [dateFormat setDateFormat:@"yyyy-MM"];
    return [dateFormat stringFromDate:date];
}

- (IBAction)AllBillAction:(id)sender {
    GRAllBillViewController * allBillVC = [[GRAllBillViewController alloc]init];
    WEAKSELF
    allBillVC.successReturnBlock = ^{
        [weakSelf loadData];
    };
    [self.navigationController pushViewController:allBillVC animated:YES];
}

- (IBAction)StageRecordAction:(id)sender {
    
//    GRInTheInstallmentViewController * recordVC = [[GRInTheInstallmentViewController alloc]init];
//    [self.navigationController pushViewController:recordVC animated:YES];
    
}


-(void)updateDate{
    self.currentDateLabel.text = [NSString stringWithFormat:@"%ld年%ld月",[[[self.month componentsSeparatedByString:@"-"] firstObject] integerValue],  [[[self.month componentsSeparatedByString:@"-"] lastObject] integerValue]] ;
    if (_isBill) {
        self.nextArrow.hidden = YES;
        self.nextMonth.hidden = YES;
        self.lastMonth.hidden = YES;
        self.lastArrow.hidden = YES;
    }else{
        int result = [self compareOneDay:self.month];
    if (result == 0 ||result ==1) {
        self.nextMonth.hidden = YES;
        self.nextArrow.hidden = YES;
    }else{
        self.nextMonth.hidden = NO;
        self.nextArrow.hidden = NO;
        NSString * nextDate = [[[self getLastOrNextMonthWithDate:self.month Month:1] componentsSeparatedByString:@"-"]lastObject];
        [self.nextMonth setTitle:[NSString stringWithFormat:@"%ld月",[nextDate integerValue]] forState:UIControlStateNormal];
    }
  if ([_billModel.firstMonth isKindOfClass:[NSNull class]] ||_billModel.firstMonth == nil) {
            self.lastArrow.hidden = YES;
            self.lastMonth.hidden = YES;
        }else{
            int lastResult  =   [self compareOneDay:[self getLastOrNextMonthWithDate:self.month Month:-1] Otherday:self.billModel.firstMonth];
            if (lastResult == 1) {
                self.lastArrow.hidden = NO;
                self.lastMonth.hidden = NO;
                NSString * lastDate = [[[self getLastOrNextMonthWithDate:self.month Month:-1] componentsSeparatedByString:@"-"] lastObject];
                [self.lastMonth setTitle:[NSString stringWithFormat:@"%ld月",[lastDate integerValue]] forState:UIControlStateNormal];
            }else{
            self.lastArrow.hidden = YES;
            self.lastMonth.hidden = YES;
            }
        }
    }
    
}

-(int)compareOneDay:(NSString *)oneday Otherday:(NSString *)otherDay{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM"];
    NSDate *oneDate = [dateFormatter dateFromString:oneday];
    NSDate * OtherDate = [dateFormatter dateFromString:otherDay];
     NSComparisonResult result = [oneDate compare:OtherDate];
    if (result == NSOrderedAscending ) {
        return -1;
    }else{
        return 1;
    }
}

-(int)compareOneDay:(NSString *)nextMonth
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM"];
    NSString * currentStr = [dateFormatter stringFromDate:[NSDate date]];
    NSDate *nextDate = [dateFormatter dateFromString:nextMonth];
    NSDate * currentDate = [dateFormatter dateFromString:currentStr];
    
    NSComparisonResult result = [nextDate compare:currentDate];
    
    if (result == NSOrderedDescending) {
        //NSLog(@"oneDay比 anotherDay时间晚");
        return 1;
    }
    else if (result == NSOrderedAscending){
        //NSLog(@"oneDay比 anotherDay时间早");
        return -1;
    }
    //NSLog(@"两者时间是同一个时间");
    return 0;
    
}

-(void)loadData{
      [GRHUD showLoading:@"玩命加载中" atView:self.view];
    [self.monthBillAction  getMonthBill:self.month CompleteBlock:^(BOOL success, id responseObject, GRError *error) {
        [GRHUD dismissHUD:self.view];
        NSLog(@"%@",responseObject);
        if (success) {
            self.billModel = [GRAllBillModel yy_modelWithDictionary:responseObject];
            [self updateDate];
            if (self.billModel.allOverdue &&_isBill) {
         
                self.allOverdueTip.hidden = NO;
                self.allOverdueImage.hidden = NO;
                self.monthListTop.constant = 94;
            }else{
                self.allOverdueTip.hidden = YES;
                self.allOverdueImage.hidden = YES;
               self.monthListTop.constant = 64;
            }
            if (self.billModel.status == 0) {//待偿还
                self.outstandingView.hidden = NO;
                self.payBt.hidden = NO;
                self.headerView.frame = CGRectMake(0, 0, KscreenWidth, 215);
                if ( _isBill){
                     self.footView.frame =CGRectMake(0, 0, KscreenWidth, 285);
                }else{
                    self.footView.frame =CGRectMake(0, 0, KscreenWidth, 165);
                }
                  self.bottomViewHeght.constant = 165;
               
            }else{//已还清
                self.headerView.frame = CGRectMake(0, 0, KscreenWidth, 255);
                 self.outstandingView.hidden = YES;
                self.payBt.hidden = YES;
                if (_isBill) {
                    self.footView.frame =CGRectMake(0, 0, KscreenWidth, 245);
                }else{
                    self.footView.frame =CGRectMake(0, 0, KscreenWidth, 125);
                }
                 self.bottomViewHeght.constant = 125;
            }
            
            self.cellTypeArr = nil;
            if ([responseObject[@"id"] isKindOfClass:[NSNull class]]) {
                self.placeIamgeview.hidden = NO;
                self.noBillView.hidden = NO;
                self.headerView.frame =CGRectMake(0, 0, KscreenWidth, 245);
                if (_isBill) {
                     self.footView .frame = CGRectMake(0, 0, KscreenWidth, 285);
                }else{
                     self.footView .frame = CGRectMake(0, 0, KscreenWidth, 165);
                }
            }else{
                self.placeIamgeview.hidden = YES;
                self.noBillView.hidden = YES;
            if (self.billModel.isOverdue) {//逾期
                self.cellTypeArr  = @[@(monthBillCelltypePrice),@(monthBillCelltypeOverdue),@(monthBillCelltypeBegPrice)];
                self.OverdueView.hidden = NO;
                self.OverdueLabel.text = [NSString stringWithFormat:@"%ld天", self.billModel.overdueDay];
            }else{
                self.cellTypeArr  = @[@(monthBillCelltypePrice),@(monthBillCelltypeBegPrice)];
                self.OverdueView.hidden = YES;
            }
            }
            self.saveTimeLabel.text = self.billModel.saveTime;
            self.outDateLabel.text = self.billModel.outDate;
            self.lastDayLabel.text = self.billModel.lastDayCN;
            self.totalPriceLabel.text = [NSString stringWithFormat:@"%.2lf",self.billModel.price];
            self.monthBillList.tableHeaderView = self.headerView;
            self.monthBillList.tableFooterView = self.footView;
            [self.monthBillList reloadData];
        }else{
            [error errorAlertWithUIView:self.view offsetY:0 completion:^{
                [self loadData];
            }];
        }
    }];
}



-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    GRMonthBillTableViewCell * billCell = [tableView dequeueReusableCellWithIdentifier:@"monthBillCell" forIndexPath:indexPath];
    billCell.monthCellType = [self.cellTypeArr[indexPath.row] integerValue];
    billCell.billModel = self.billModel;
    return billCell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _cellTypeArr.count;
    
}

- (IBAction)returnAction:(id)sender {
    GRRepaymentViewController * refundVC = [[GRRepaymentViewController  alloc]init];
    refundVC.refunType = RefundTypeMonth;
    refundVC.timeStr =  [NSString stringWithFormat:@"%@月还款",self.month];
    refundVC.stagesId = self.billModel.id;
    refundVC.price = self.billModel.price;
WEAKSELF
    refundVC.successBlock = ^{
        [weakSelf loadData];
        if (self.returnPaySuccess !=nil) {
            self.returnPaySuccess();
        }
    };
    [self.navigationController pushViewController:refundVC animated:YES];
}

- (IBAction)lastMonthAction:(id)sender {
    NSString * lastMonthStr =   [self getLastOrNextMonthWithDate:self.month Month:-1];
    self.month = lastMonthStr;
    [self loadData];
    NSLog(@"%@",lastMonthStr );
}


- (IBAction)nextMonthAction:(id)sender {
    NSString * nextMonthStr =   [self getLastOrNextMonthWithDate:self.month Month:1];
    self.month = nextMonthStr;
    [self loadData];
    NSLog(@"%@",nextMonthStr );
    
}

- (IBAction)skipToMonthBillAction:(id)sender {
    GRMonthBillViewController * monthBillVC = [[GRMonthBillViewController alloc]init];
    monthBillVC.month = self.billModel.overdueMonth;
    [self.navigationController pushViewController:monthBillVC animated:YES];
}


-(NSString *)getLastOrNextMonthWithDate:(NSString *)dateString Month:(NSInteger)month
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM"];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *lastMonthComps = [[NSDateComponents alloc] init];
    [lastMonthComps setMonth:month];
    NSDate *newdate = [calendar dateByAddingComponents:lastMonthComps toDate:  [formatter dateFromString:dateString] options:0];
    NSString *dateStr = [formatter stringFromDate:newdate];
    NSLog(@"date str = %@", dateStr);
    return dateStr;
}

- (IBAction)goShoppingAction:(id)sender {
    [MSTabBarController seletedTabIndex:0];
    [self.navigationController popToRootViewControllerAnimated:YES];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
